<template>
  <div class="role-page">
    <div class="btns-fun-field">
      <!-- v-if="rolePermission.addRolePerm" -->
      <el-button
        type="primary"
        @click.prevent="showAddEditDialog({})"
        :icon="Plus"
      >
        新增权限
      </el-button>
    </div>
    <div class="table-field">
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        v-loading="tableLoading"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'true' }"
      >
        <el-table-column prop="permissionName" label="权限别名" width="200" />
        <el-table-column prop="typeName" label="菜单类型" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.type == 1" type="primary">{{
              row.typeName
            }}</el-tag>
            <el-tag v-if="row.type == 2" type="success">{{
              row.typeName
            }}</el-tag>
            <el-tag v-if="row.type == 3" type="warning">{{
              row.typeName
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="permissionCode" label="权限code" width="400" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" min-width="180px" fixed="right">
          <template #default="scope">
            <el-button
              v-if="scope.row.type != 3"
              type="primary"
              size="small"
              @click.prevent="showAddEditDialog(scope.row)"
              >新增权限</el-button
            >
            <!-- v-if="rolePermission.removeRolePerm" -->
            <el-button
              type="danger"
              size="small"
              @click.prevent="showRemoveDialog(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-field">
      <el-pagination
        v-model:current-page="formData.pageIndex"
        v-model:page-size="formData.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="formData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-if="addDialogVisible"
      v-model="addDialogVisible"
      :title="addEditForm.title"
      width="550px"
    >
      <div style="padding-right: 50px">
        <el-form
          :model="addEditForm"
          :rules="addEditRules"
          ref="addEditRef"
          :label-width="80"
        >
          <el-form-item
            v-if="addEditForm.parentId"
            label="parentId"
            prop="permissionName"
          >
            <el-input
              disabled
              :value="`${addEditForm.parentPerssionName}(${addEditForm.parentPerssionCode})`"
              autocomplete="off"
              placeholder="请输入权限别名"
            />
          </el-form-item>
          <el-form-item label="权限类型" prop="permId">
            <el-select v-model="addEditForm.type" placeholder="选择权限类型">
              <el-option
                v-for="option in curCanSelectedTypeList"
                :key="option.id"
                :label="option.name"
                :value="option.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="权限别名" prop="permissionName">
            <el-input
              v-model="addEditForm.permissionName"
              autocomplete="off"
              placeholder="请输入权限别名"
            />
          </el-form-item>
          <el-form-item label="权限code" prop="permissionCode">
            <el-input
              v-model="addEditForm.permissionCode"
              autocomplete="off"
              placeholder="请输入权限code(需要唯一)"
            />
          </el-form-item>

          <el-form-item label="备注说明" prop="remark">
            <el-input
              v-model="addEditForm.remark"
              :rows="4"
              type="textarea"
              autocomplete="off"
              placeholder="请输入备注说明"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="startAddPermission">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-if="removeDialogVisible"
      v-model="removeDialogVisible"
      title="删除权限"
      width="400px"
    >
      <span>确定要删除当前权限？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="removeDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="startRemovePermission">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import {
  getPermissionPagination,
  addPermission,
  removePermission,
} from '@/api/ums-user.api'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, selectKey, FormInstance } from 'element-plus'
import { useRolePermission } from '@/utils/permission.utils'
const rolePermission = useRolePermission()
const formData = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

const props = {
  label: 'menuName',
  children: 'children',
}

interface PemissionItem {
  id: number
  name: string
}
const permissionTypeList: Array<PemissionItem> = [
  {
    id: 1,
    name: '菜单文件夹',
  },
  {
    id: 2,
    name: '菜单',
  },
  {
    id: 3,
    name: '按钮',
  },
]
const curCanSelectedTypeList = ref<PemissionItem[]>([])

const removeDialogVisible = ref(false)
const addDialogVisible = ref(false)
const addEditRef = ref<FormInstance>()
const addEditForm = reactive({
  id: null,
  parentId: 0,
  parentPerssionCode: '',
  parentPerssionName: '',
  permissionName: '',
  permissionCode: '',
  type: '',
  remark: '',
  disabled: false,
  title: '',
})

const addEditRules = reactive({
  name: [
    { required: true, message: '请输入权限名', trigger: 'blur' },
    { min: 1, max: 30, message: '长度为1~30位', trigger: 'blur' },
  ],
})

const showAddEditDialog = (item: any) => {
  if (item.id) {
    curCanSelectedTypeList.value = permissionTypeList.filter((row) => {
      return item.type < row.id
    })
  } else {
    curCanSelectedTypeList.value = permissionTypeList
  }

  addEditForm.id = null
  addEditForm.parentId = item.id || 0
  addEditForm.type = ''
  addEditForm.parentPerssionCode = item.permissionCode || ''
  addEditForm.parentPerssionName = item.permissionName || ''
  addEditForm.permissionName = ''
  addEditForm.permissionCode = ''
  addEditForm.remark = ''
  addEditForm.disabled = false
  addEditForm.title = '新增权限'
  addDialogVisible.value = true
}

const tableLoading = ref(false)
const tableData = ref([])

const curSelectRow = ref('')
const showRemoveDialog = (item: any) => {
  removeDialogVisible.value = true
  curSelectRow.value = item
  console.log('item: ', item)
}

const startRemovePermission = () => {
  let id = curSelectRow.value?.id
  removePermission([id])
    .then((res) => {
      console.log('success~~~~~')
      removeDialogVisible.value = false
      ElMessage({
        message: '权限删除成功',
        type: 'success',
      })
      getDataList()
    })
    .catch((err) => {
      removeDialogVisible.value = false
      ElMessage({
        message: err.msg || err,
        type: 'error',
      })
    })
}

const startAddPermission = () => {
  let formData = {
    parentId: addEditForm.parentId,
    permissionName: addEditForm.permissionName,
    permissionCode: addEditForm.permissionCode,
    type: addEditForm.type,
    remark: addEditForm.remark,
  }

  if (!addEditRef.value) return
  addEditRef.value.validate((valid, fields) => {
    if (valid) {
      if (addEditForm.id) {
        // updateRole({
        //   ...formData,
        //   id: addEditForm.id,
        // })
        //   .then((res) => {
        //     addDialogVisible.value = false;
        //     ElMessage({
        //       message: "权限修改成功",
        //       type: "success",
        //     });
        //     getDataList();
        //   })
        //   .catch((err) => {
        //     ElMessage({
        //       message: err.msg || err,
        //       type: "error",
        //     });
        //   });
        return
      }

      addPermission(formData)
        .then((res) => {
          addDialogVisible.value = false
          ElMessage({
            message: '权限新增成功',
            type: 'success',
          })
          getDataList()
        })
        .catch((err) => {
          ElMessage({
            message: err.msg || err,
            type: 'error',
          })
        })
    }
  })
}

const handleSizeChange = (value: number) => {
  console.log('handleSizeChange...', value)
  formData.pageSize = value
  getDataList()
}

const handleCurrentChange = (value: number) => {
  console.log('handleCurrentChange...', value)
  formData.pageIndex = value
  getDataList()
}

const getDataList = () => {
  tableLoading.value = true
  getPermissionPagination({
    pageSize: formData.pageSize,
    pageIndex: formData.pageIndex,
  })
    .then(function (res: any) {
      tableLoading.value = false
      console.log('.......................')
      console.log(res)
      console.log('.......................')
      let list = res.list || []
      const changeTypeName = (value: number) => {
        if (value == 1) {
          return '菜单目录'
        } else if (value == 2) {
          return '菜单项'
        } else if (value == 3) {
          return '按钮'
        }
      }
      list = list.map((item: any) => {
        item.typeName = changeTypeName(item.type)
        if (item.children) {
          item.children = item.children.map((child: any) => {
            child.typeName = changeTypeName(child.type)
            return child
          })
        }
        return item
      })

      tableData.value = res.list || []
      formData.total = Number(res.total)
    })
    .catch((error) => {
      console.log(error)
      tableLoading.value = false
    })
}

const permissionList = ref([])
const flatPermissionList = ref([])
const checkedKeys = ref<any>([])

onMounted(() => {
  getDataList()
})
</script>
<style lang="scss" scoped>
.role-page {
  background-color: #fff;
  padding: 20px;
  max-height: calc(100vh - 134px);
}

.btns-fun-field {
  margin-bottom: 20px;
}

.pagination-field {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.btn-inner {
  display: flex;
  justify-content: center;
  color: #fff;
}
</style>
